package com.liangwei.productAndConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JUG版本的生产者与消费者的问题
 */
public class jugPc {
    public static void main(String[] args) {
        //创建消耗的资源
        Data data = new Data();
        //创建线程
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者D").start();
    }

    //创建资源类
    static class Data {
        //创建资源
        private int number = 0;
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        //创建资源的方法
        public void increment() throws InterruptedException {
            //上锁
            lock.lock();
            //进行等待判断
            try {
                while (number != 0) {
                    condition.await();
                }
                number++;
                System.out.println(Thread.currentThread().getName() + "=========>" + number);
                //唤醒线程
                condition.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放锁
                lock.unlock();
            }
        }

        public void decrement() throws InterruptedException {
            //上锁
            lock.lock();
            //进行等待的判断
            try {
                while (number == 0) {
                    condition.await();
                }
                number--;
                System.out.println(Thread.currentThread().getName() + "=========>" + number);
                //通知其他线
                condition.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //释放锁
                lock.unlock();
            }
        }
    }
}
